#include <stdio.h>
#include <string.h>

#include "response.h"
#include "log.h"

static int send_response(connection* connect, const char* message)
{
	http_pair *pair;
	char response[DEFAULT_LIMIT_RESPONSE_DATASIZE + 1024];
	char *ppp = response;
	sprintf(ppp, "%s %d %s" CRLF, http_version_message(connect->response.version),
		connect->response.http_status, message);

	ppp += strlen(ppp);
	for(pair = connect->response.entry; pair != NULL; pair = pair->next) {
		sprintf(ppp, "%s: %s" CRLF, pair->name, pair->value);
		ppp += strlen(ppp);
	}

	sprintf(ppp, CRLF "%s" CRLF, message);
	ppp += strlen(ppp);
	return tcp_write(connect->client, response, ppp - response);
}

int do_response_process(connection *connect)
{
	if(connect->client->keep_alive == 1)
		http_pair_push(&(connect->response.tail), new_pair(HTTP_HEADER_CONNECTION   , "close"));
	else
		http_pair_push(&(connect->response.tail), new_pair(HTTP_HEADER_CONNECTION   , "Keep-Alive"));	

	return send_response(connect, http_stat_message(connect->response.http_status));
}

